package com.foosun.util;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class ImageUtils {
	/*
	 * 图片服务器域名
	 */
	public static String IMG_SERVER_DOMAIN = "static.eop.com";
	
	/**
	 * 删除图片
	 * 
	 * @param filePath
	 */
	public static void delete(String filePath) {
		try {
			File file = new File(filePath);
			if (file.exists()){
				file.delete();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public static InputStream getResourceAsStream(String resource) {
		String stripped = resource.startsWith("/") ? resource.substring(1)
				: resource;

		InputStream stream = null;
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		if (classLoader != null) {
			stream = classLoader.getResourceAsStream(stripped);

		}
	
		return stream;
	}
	
	/**
	 * 得到根目录绝对路径(不包含WEB-INF)
	 * 
	 * @return
	 */
	public static String getRootPath() {
		String filePath = Thread.currentThread().getContextClassLoader()
				.getResource("").toString();
		if (filePath.toLowerCase().indexOf("file:") > -1) {
			filePath = filePath.substring(6, filePath.length());
		}
		if (filePath.toLowerCase().indexOf("classes") > -1) {
			filePath = filePath.replaceAll("/classes", "");
		}
		if (filePath.toLowerCase().indexOf("web-inf") > -1) {
			filePath = filePath.substring(0, filePath.length() - 9);
		}
		if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0) {
			filePath = "/" + filePath;
		}

		if (filePath.endsWith("/"))
			filePath = filePath.substring(0, filePath.length() - 1);

		return filePath.replace("goom", "gogo");//FIXME HARDCODE
	}	
	
	public static void main(String[] args){
		System.out.println(ImageUtils.getRootPath());
	}
	
	/**
	 * 验证一个字符串是否为空
	 * @param str
	 * @return 如果为空返回真，如果不为空返回假
	 * 2014-01-21
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str))
			return true;

		String pattern = "\\S";
		Pattern p = Pattern.compile(pattern, 2 | Pattern.DOTALL);
		Matcher m = p.matcher(str);
		return !m.find();
	}
	
	/**
	 * 替换图片域名
	 * @param path
	 * @return
	 */
	public static String replacePath(String path){	
		if(isEmpty(path)) return path;
		return path.replaceAll("fs:", IMG_SERVER_DOMAIN);	
	}
	
	static {
		try {
			InputStream in = getResourceAsStream("server.properties");
			Properties props = new Properties();
			props.load(in);
			init(props);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void init(Properties props) {

		String domain = props.getProperty("domain.imageserver");
		IMG_SERVER_DOMAIN = isEmpty(domain) ? IMG_SERVER_DOMAIN : domain;
		IMG_SERVER_DOMAIN = IMG_SERVER_DOMAIN.startsWith("http://") ? IMG_SERVER_DOMAIN : "http://" + IMG_SERVER_DOMAIN;
		
	}
	
}
